/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.basics.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Member;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Promotion;
import com.rzico.basics.model.ProductMeta;
import com.rzico.basics.model.ProductVo;
import com.rzico.basics.model.PromotionVo;
import com.rzico.basics.service.MemberService;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.entity.Pageable;
import com.rzico.entity.PageResult;
import com.rzico.basics.entity.Product;
import com.rzico.basics.service.ProductService;
import com.rzico.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.Api;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

/**
 * 产品档案控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-02-17
 */
@Api(description = "产品档案接口")
@RestController
@RequestMapping("/product")
public class ProductController extends BaseController {

    @Autowired
    private ProductService productService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private EnterpriseService enterpriseService;

    /**
     * 分页查询产品档案
     *
     * @return
    */
    @ApiOperation("分页查询产品档案")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mchId", value = "商户号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "productCategoryId", value = "分类 id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "brandId", value = "品牌 id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "商品名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startPrice", value = "开始价格", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endPrice", value = "结束价格", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "tagIds", value = "标签过滤", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键字", dataType = "String", paramType = "query")
    })
    public CommResult<Product> list(String mchId, Long productCategoryId, Integer subType, Long brandId, String name,
                                    BigDecimal startPrice,BigDecimal endPrice,Long [] tagIds,
                                    String keyword, Pageable pageable) {

        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);

        if ("create_date".equals(params.get("sortField").toString())) {
            params.put("sortField","orders");
            params.put("sortType","asc");
        }

        params.put("deleted",false);
        params.put("isList",true);
        params.put("isMarketable",true);

        Enterprise enterprise = enterpriseService.findByMch(mchId);
        if (enterprise!=null) {
            params.put("enterpriseId", enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }

        if (productCategoryId!=null) {
            params.put("treePath",String.valueOf(productCategoryId));
        }

        if (brandId!=null) {
            params.put("brandId",brandId);
        }

        if (startPrice!=null) {
            params.put("startPrice",startPrice);
        }

        if (endPrice!=null) {
            params.put("endPrice",endPrice);
        }

        if (subType!=null) {
            params.put("subType",subType);
        }

        if (name!=null) {
            params.put("name",name);
        }

        if (tagIds!=null && tagIds.length>0) {
            params.put("tagIds",tagIds);
        }

        if (StringUtils.isNotEmpty(keyword)) {
            params.put("keyword",keyword);
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<ProductVo> list = productService.selectProductVoList(params);

        Member member = memberService.getCurrent();
        //获取全场活动
        //TODO
        for (ProductVo product:list) {

            Map<String,Object> prm = new HashMap<>();
            prm.put("goodsId",product.getGoodsId());
            Integer rw = productService.selectRowCount(prm);
            product.setSku(rw);

            if (member!=null && member.getVvip().compareTo(1)>0) {
                product.setVipPrice(product.getMemberPrice(member));
            } else {
                product.setVipPrice(product.getVip1price());
                if (product.getVipPrice().compareTo(BigDecimal.ZERO)==0) {
                    product.setVipPrice(product.getPrice());
                }
            }

            if (member!=null && member.getAmount().compareTo(BigDecimal.ZERO)>0) {
                List<PromotionVo> pvo = new ArrayList<>();
                for (PromotionVo vo:product.getPromotions()) {
                    if (vo.getType().equals(10)) {
                        continue;
                    }
                    if (vo.getFirsted()) {
                        continue;
                    }
                    if (product.getFreightId()==null && vo.getType().equals(6)) {
                        continue;
                    }
                    pvo.add(vo);
                }
                product.setPromotions(pvo);
            }

        }

        PageResult<ProductVo> pageResult = new PageResult<ProductVo>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);

    }

    /**
     * 查询单条产品档案
     *
     * @return
    */
    @ApiOperation("查询单条产品档案")
    @GetMapping("/find/{id}")
    public CommResult<Product> find(@PathVariable String id) {

        Product result = productService.findById(id);
        Member member = memberService.getCurrent();
        Map<String,Object> params = new HashMap<>();
        params.put("goodsId",result.getGoodsId());
        if (member!=null) {
            params.put("vipId", member.getVvip());
        }
        params.put("deleted",false);

        params.put("sortField", "is_list");
        params.put("sortType", "desc");

        List<ProductVo> products = productService.selectProductVoList(params);

        Map<String,Object> data = new HashMap<>();
        data.put("products",products);

        Map<String,Object> articleParams = new HashMap<>();
        articleParams.put("goods",result.getGoodsId());

        //详情
        ProductMeta metas = new ProductMeta();
        if (result.getMeta()!=null) {
            metas = JSON.parseObject(result.getMeta(), ProductMeta.class);
        }
        if (metas.getImages().size()==0) {
            List<String> imageList = new ArrayList<>();
            imageList.add(result.getThumbnail());
            metas.setImages(imageList);
        }
        data.put("meta",metas);

        data.put("content",result.getContent());

        for (ProductVo product:products) {
            product.setSku(products.size());
            if (member!=null && member.getVvip().compareTo(1)>0) {
                product.setVipPrice(product.getMemberPrice(member));
            } else {
                product.setVipPrice(product.getVip1price());
                if (product.getVipPrice().compareTo(BigDecimal.ZERO)==0) {
                    product.setVipPrice(product.getPrice());
                }
            }

            if (member!=null && member.getAmount().compareTo(BigDecimal.ZERO)>0) {
                List<PromotionVo> pvo = new ArrayList<>();
                for (PromotionVo vo:product.getPromotions()) {
                    if (vo.getType().equals(10)) {
                        continue;
                    }
                    if (vo.getFirsted()) {
                        continue;
                    }
                    pvo.add(vo);
                }
                product.setPromotions(pvo);
            }

        }

        return CommResult.success(data);

    }



    /**
     * 旧系统导入商品详情
     *
     * @return
     */
    @ApiOperation("旧系统导入商品详情")
    @GetMapping("/old2New")
    public CommResult<Product> old2New(String mchId) {
        Enterprise enterprise = enterpriseService.findByMch(mchId);
        Product product = new Product();
        product.setEnterpriseId(enterprise.getId());
        List<Product> productList = productService.select(product);
        for (Product prod:productList) {
            String content = prod.getContent();
            if (content!=null) {
                try {
                    String s = "";
                    JSONArray arr = JSONArray.parseArray(content);
                    for (int i = 0; i < arr.size(); i++) {
                        JSONObject obj = arr.getJSONObject(i);
                        s = s.concat("<img style='width:100%' src='" + obj.getString("thumbnail") + "'</img>");
                    }
                    prod.setContent(s);
                    productService.updateByPrimaryKeySelective(prod);
                } catch (Exception e) {

                }
            }
        }
        return CommResult.success("导入成功");
    }


    /**
     * 旧系统导入商品详情
     *
     * @return
     */
    @ApiOperation("测试区域代理")
    @GetMapping("/test")
    public CommResult<Product> test(String mchId) {

        Map<String,Object> params = new HashMap<>();
        params.put("areaId",350200);
        //params.put("vipType",2);
        //params.put("deleted",false);
        params.put("enterpriseId",39);
        List<Member> memberList = memberService.selectList(params);

        memberService.findByAreaAgent(39L,350211);

        return CommResult.success("导入成功");
    }
}
